package demo.kafka.simple;

import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.clients.producer.RecordMetadata;

import java.util.Properties;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author linwm
 * @date 2021/8/4 22:38
 */
public class Producer {
    public static AtomicInteger key = new AtomicInteger(0);

    public static void main(String[] args) throws Exception {
        Producer producer = new Producer();
        for (int i = 0; i < 400; i++) {
            producer.test();
        }
    }

    public void test() throws Exception {
        Properties properties = new Properties();
        properties.setProperty("bootstrap.servers", "localhost:9092");
        properties.setProperty("client.id", "client-1");
        properties.setProperty("key.serializer", "org.apache.kafka.common.serialization.IntegerSerializer");
        properties.setProperty("value.serializer", "org.apache.kafka.common.serialization.StringSerializer");
        KafkaProducer<Integer, Object> producer = new KafkaProducer<>(properties);

        String topic = "topic-1";
        String msg = "message_" + key;
        Future<RecordMetadata> result = producer.send(new ProducerRecord<>(topic, key.get(), msg), new ProducerCallback(System.currentTimeMillis(), key.get(), msg));
        //等待消息发送
        result.get();
        key.addAndGet(1);
    }
}
